package de.dopichaj.labrador.index;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import de.dopichaj.labrador.index.meta.BaselineDocumentMetaDataIOFactory;
import de.dopichaj.labrador.index.meta.BaselineDocumentMetaDataWriter;
import de.dopichaj.labrador.index.meta.DocumentDigestOutputStream;
import de.dopichaj.labrador.index.meta.DocumentMetaDataWriter;
import de.dopichaj.labrador.index.selector.AllSelector;
import de.dopichaj.labrador.index.selector.IndexSelector;
import de.dopichaj.labrador.util.io.BitOutputStream;
import de.dopichaj.labrador.util.io.ByteWriter;


/**
 * A utility for making Lucene Documents from a File 
 * which should be a XML-file.
 */
public class IndexWriter implements IndexAdder {

    /**
     * A logger for this class
     */
    private static final Logger log = Logger.getLogger(IndexWriter.class);
    
    private final Index index;
    private final WritableIndex writableIndex;
    /**
     * All documents that are already in the index.
     */
    private final Set<File> indexedDocuments = new HashSet<File>();
    
    private final TagFactory tagFactory;
    private final PrintWriter tagFactoryWriter;
    private final DocumentBuilder builder;
    private final DocumentAdder adder;
    private final DocumentMetaDataWriter digestOutput;

    /**
     * Constructor.
     * 
     * @param handleCollisions see <code>handleCollisions</code> in
     *      {@link DocumentAdder#DocumentAdder(IndexAdder, Analyzer,
     *      DocumentDigestOutputStream, TagFactory, boolean, int)}
     * @param maxInlineLength
     *          see {@link DocumentAdder#DocumentAdder(IndexAdder,
     *          Analyzer, DocumentDigestOutputStream, TagFactory, boolean, int)
     * @throws IndexVersionException if trying to open an existing index of the wrong version.
     */
    public IndexWriter(Index index, IndexSelector selector, boolean create)
        throws ParserConfigurationException, IOException {
        
        Validate.notNull(index);

        this.index = index;
        this.writableIndex = index.getWritableIndex();
        
        // TODO: determine the set of known documents and the next fragment ID

        // clean up dirty de.dopichaj.labrador.index unless creating a new one
        if (!create) {
            if (index.isDirty()) {
                throw new IOException("Index is dirty.");
            }
        }        

        if (create) {
            tagFactory = new TagFactory();
        } else {
            tagFactory = index.getTagFactory();
        }
        tagFactoryWriter = index.getTagIdWriter();
        tagFactory.setWriter(tagFactoryWriter);

        // set up digest output stream
        final BaselineDocumentMetaDataIOFactory ioFactory = index.getIOFactory();
        digestOutput = new BaselineDocumentMetaDataWriter(ioFactory,
            new BitOutputStream(new ByteWriter(
                new DataOutputStream(index.getDigestOutputStream()), 2048)));

        // set up XML Parser
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // workaround for JRE 6 bug
        try {
            factory.setFeature(
                "http://apache.org/xml/features/dom/defer-node-expansion",
                false);
        } catch (ParserConfigurationException e) {
            log.warn("Could not enable deferring node expansion.");
        }
        builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new CatalogResolver());
        
        // mark de.dopichaj.labrador.index as dirty
        index.markAsDirty();

        adder = new DocumentAdder(this, index.getTokenizer(), digestOutput,
            tagFactory, selector, index.getConfiguration());
    }

    /**
     * Open an existing index for update.
     * @param indexDirectory
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws IndexVersionException
     */
    public IndexWriter(Index index, boolean handleCollisions)
        throws ParserConfigurationException, IOException {
        
        this(index, new AllSelector(), false);
    }

    /**
     * Makes a number of XML-document-fragments from a File.
     * @throws IOException
     * @throws SAXException 
     */
    public void addDocument(File f)
            throws IOException, SAXException {

        Validate.notNull(f);
        
        FileInputStream is = new FileInputStream(f);
        Reader reader = new BufferedReader(new InputStreamReader(is));
        
        addFromReader(reader, f);
    }

    /**
     * Add a new document from a reader.
     * 
     * @param reader the reader from which to read the document (unusable after
     *               this method returns).
     * @param filePath the identifier for this document.
     * @throws IOException
     * @throws SAXException
     */
    public void addFromReader(Reader reader, File filePath)
        throws IOException, SAXException {
        
        Validate.notNull(reader);
        Validate.notNull(filePath);

        // if this file has already been indexed, don't de.dopichaj.labrador.index it again
        if (indexedDocuments.contains(filePath.getAbsoluteFile())) {
            log.info("Skipping already indexed file " + filePath);
            return;
        }
        
        log.info("Indexing " + filePath);

        digestOutput.startDocument(filePath);
        writableIndex.startNewDocument();

        InputSource inputSource = new InputSource(reader);
        org.w3c.dom.Document xmlDocument = builder.parse(inputSource);
        adder.addDocument(xmlDocument);
        
        digestOutput.endDocument();
    }

    /**
     * Add a fragment to the index.
     * @throws IOException 
     */
    public void addToIndex(int fragmentID, String xPath, List<String> tokens,
        int length, int position) throws IOException {

        Validate.notNull(xPath);
        Validate.notNull(tokens);
        Validate.isTrue(length >= 0);
        Validate.isTrue(position >= 0);

        writableIndex.addToIndex(fragmentID, xPath, tokens, length, position);
    }

    /**
     * Close this filer and clean up.
     * @throws IOException 
     * @throws IOException
     */
    public void close() throws IOException {
        try {
            index.storeMetaData(adder.getDocumentCount(),
                adder.getElementCount(), adder.getLengthSum());
            writableIndex.close();
        } finally {
            try {
                digestOutput.close();
            } catch (IllegalStateException e) {
                log.warn("Illegal state closing digest (probably caused by previous" +
                        "exceptions)", e);
            } finally {
                tagFactoryWriter.close();
            }
        }
        
        if (tagFactoryWriter.checkError()) {
            throw new IOException("Error writing tag ID file.");
        }

        index.markAsClean();
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/